package middleware

import (
	"main/handlers"
	"net/http"
	"strings"

	"github.com/gin-gonic/gin"
)

// AppRequest 结构体表示通用的项目请求参数
type AppRequest struct {
	AppId                   int    `json:"app_id"`                      // 应用 ID（可选，删除或更新时需要）
	HostId                  int    `json:"host_id" binding:"required"`  // 主机 ID（必填）
	AppName                 string `json:"app_name" binding:"required"` // 应用名称编码（必填）
	AppNowStatusAlarmConfig int    `json:"app_now_status_alarm_config"` // 应用当前状态（可选）
	AppCpuAlarmConfig       int    `json:"app_cpu_alarm_config"`        // 应用当前CPU（可选）
	AppMemAlarmConfig       int    `json:"app_mem_alarm_config"`        // 应用当前内存（可选）
	AppDiskAlarmConfig      int    `json:"app_disk_alarm_config"`       // 应用当前硬盘（可选）
	AppLinkAlarmConfig      int    `json:"app_link_alarm_config"`       // 应用当前连接数（可选）
	AppInstruction          string `json:"app_instruction"`             // 备注（可选）
}

// GetApp 处理获取项目数据的请求
func GetApp(c *gin.Context) {
	query := `
		SELECT c.project_name,c.project_id, b.host_name, b.host_id, a.* FROM app a
		LEFT JOIN hosts b ON a.host_id = b.host_id
		LEFT JOIN project c ON b.project_id = c.project_id
		WHERE app_del != 1
	`

	results, err := handlers.ExecuteQuery(query)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "查询应用数据失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, results)
}

// PostApp 处理新建项目的请求
func PostApp(c *gin.Context) {
	var app AppRequest

	if err := c.ShouldBindJSON(&app); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的数据", "details": err.Error()})
		return
	}

	query := "INSERT INTO app (`host_id`, `app_name`, `app_now_status_alarm_config`, `app_cpu_alarm_config`, `app_mem_alarm_config`, `app_disk_alarm_config`, `app_link_alarm_config`, `app_instruction`) VALUES (?, ?, ?, ?, ?, ?, ?, ?)"
	_, err := handlers.ExecuteNonQuery(query, app.HostId, app.AppName, app.AppNowStatusAlarmConfig, app.AppCpuAlarmConfig, app.AppMemAlarmConfig, app.AppDiskAlarmConfig, app.AppLinkAlarmConfig, app.AppInstruction)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "创建应用失败", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "应用创建成功"})
}

// PutApp 处理更新项目的请求
func PutApp(c *gin.Context) {
	var app AppRequest

	if err := c.ShouldBindJSON(&app); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的数据", "details": err.Error()})
		return
	}

	if app.AppId == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "应用ID是必须的"})
		return
	}

	query := `
		UPDATE app
		SET host_id = ?, app_name = ?, app_now_status_alarm_config = ?, app_cpu_alarm_config = ?, app_mem_alarm_config = ?, app_disk_alarm_config = ?, app_link_alarm_config = ?, app_instruction = ?
		WHERE app_id = ?
	`
	_, err := handlers.ExecuteNonQuery(query, app.HostId, app.AppName, app.AppNowStatusAlarmConfig, app.AppCpuAlarmConfig, app.AppMemAlarmConfig, app.AppDiskAlarmConfig, app.AppLinkAlarmConfig, app.AppInstruction, app.AppId)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "无法更新应用", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "应用更新成功"})
}

// DeleteApp 处理删除项目的请求
func DeleteApp(c *gin.Context) {
	var apps []AppRequest

	if err := c.ShouldBindJSON(&apps); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": "无效的数据", "details": err.Error()})
		return
	}

	appIDs := make([]interface{}, len(apps))
	placeholders := make([]string, len(apps))
	for i, app := range apps {
		if app.AppId == 0 {
			c.JSON(http.StatusBadRequest, gin.H{"error": "包含违规的应用ID"})
			return
		}
		appIDs[i] = app.AppId
		placeholders[i] = "?"
	}

	query := `
		UPDATE app
		SET app_del = 1
		WHERE app_id IN (` + strings.Join(placeholders, ",") + `)
	`

	_, err := handlers.ExecuteNonQuery(query, appIDs...)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "无法删除应用", "details": err.Error()})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "应用删除成功"})
}
